package com.crcode.crm.controller.data;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.crcode.crm.bean.data.EnterpriseBean;
import com.crcode.crm.bean.log.DataLogBean;
import com.crcode.crm.bean.user.UserBean;
import com.crcode.crm.service.data.EnterpriseService;
import com.crcode.crm.service.log.DataLogService;
import com.crcode.crm.service.retrieval.RetrievalService;
import com.crcode.crm.utils.DateUtil;
import com.crcode.crm.utils.MyFileUtil;
import com.crcode.crm.utils.PageVo;
import com.crcode.crm.utils.ResultPageUtil;
import com.crcode.crm.utils.ResultUtil;

@RestController
@RequestMapping("/enterprise")
public class EnterpriseController {

    @Autowired
    EnterpriseService enterpriseService;
    
    @Autowired
	private RetrievalService retrievalService;

    @Autowired
    DataLogService logService;

    /**
     * 获取单个对象
     * @param request request
     * @param session session
     * @param id id
     * @return
     */
    @RequestMapping(value ="/get", method = RequestMethod.GET)
    public EnterpriseBean get(HttpServletRequest request, HttpSession session, String id) {
        if(StringUtils.isNotBlank(id)) {
            return enterpriseService.getById(Integer.parseInt(id));
        }
        return null;
    }
    
	/**
	 * 获取单个对象
	 * @author lxw
	 * @date 2019年4月16日
	 * @param request
	 * @param session
	 * @param uuid
	 * @return
	 */
    @RequestMapping(value ="/getUuid", method = RequestMethod.GET)
    public EnterpriseBean getUuid(HttpServletRequest request, HttpSession session, String uuid) {
        
    	return this.enterpriseService.findByUuid(uuid);
    }

    /**
     * 保存企业信息
     * @param request request
     * @param session session
     * @param enterprise enterprise
     * @return Map<String, Object>
     */
    @RequestMapping(value ="/save", method = RequestMethod.POST)
    public ResultUtil saveAdd(HttpServletRequest request, HttpSession session, EnterpriseBean enterprise) {
    	ResultUtil ru = new ResultUtil();
        Object obj = session.getAttribute("user");
        if(obj == null) {
        	ru.setStatus(false);
            ru.setInfo("未登录，请先登录");
            return ru;
        }
        UserBean user = JSONObject.parseObject(obj.toString(), UserBean.class);
        
        String thisTimeStr = DateUtil.DateToStr(new Date(), "yyyy-MM-dd HH:mm:ss");
        
        
        // 准备需要保存的数据
        String beforeSaveBean = null;// 保存之前的对象JSON，后面存日志
        String remarks = null; // 日志标识新增还是编辑
        
        // 名称查重
        if(enterprise.getId()==null){//新增
        	 List<EnterpriseBean> enterpriseBean = enterpriseService.findByEntName(enterprise.getEntName());
             if(enterpriseBean.size() > 0) {
            	 ru.setStatus(false);
                 ru.setInfo("企业名称已存在");
                 return ru;
             }
             enterprise.setLiableUserUuid(user.getUuid()); 
             enterprise.setLiableUserName(user.getUserRealName()); 
             enterprise.setCreateUserUuid(user.getUuid()); 
             enterprise.setCreateUserName(user.getUserRealName());
             enterprise.setCreateTime(thisTimeStr);
             remarks = "企业资源新增";
        }else{
        	List<EnterpriseBean> enterpriseBean = enterpriseService.findByEntNameAndUuidNot(enterprise.getEntName(),enterprise.getUuid());
            if(enterpriseBean.size() > 0) {
            	ru.setStatus(false);
                ru.setInfo("企业名称已存在");
                return ru;
            }
            beforeSaveBean = JSON.toJSONString(enterpriseService.getById(enterprise.getId()));
            remarks = "企业资源编辑";
        }
        enterprise.setLastEditTime(thisTimeStr); // 设置最后编辑时间
        // 开始保存
        boolean is = enterpriseService.saveResultBoolean(enterprise);
        ru.setInfo(is ? "操作成功！" : "操作失败!");
		ru.setStatus(is);
		ru.setObj(enterprise);
		
        // 日志的处理
        DataLogBean log = new DataLogBean();
        log.setUserUuid(user.getUuid());
        log.setUserName(user.getUserRealName());
        log.setOperateTime(thisTimeStr);
        log.setDataTuid(enterprise.getUuid());
        log.setDataTitle(enterprise.getEntName());
        log.setOriginalContent(beforeSaveBean);
        log.setLatestContent(JSON.toJSONString(enterprise));
        log.setOperateRemarks(remarks);
        log.setLogType(0);
        log.setDetailedType(0);
        logService.saveResultBean(log);
        
        return ru;
    }

    /**
     * 管理页面搜索和排序的列表
     * @return ResultPageUtil
     */
    @RequestMapping(value="/list", method = RequestMethod.POST)
    public ResultPageUtil listANdSearch(HttpServletRequest request, HttpSession session, PageVo vo, String text) {
        return this.enterpriseService.findByEntNameContaining(text, vo);
    }

    /**
     * 删除多个企业,一个企业也可以调用此方法
     * @return ResultUtil
     */
    @RequestMapping(value="/delete", method = RequestMethod.POST)
    public ResultUtil delete(HttpServletRequest request, HttpSession session, String ids){
        ResultUtil resultUtil = new ResultUtil();
        Object obj = session.getAttribute("user");
        if(obj == null) {
            resultUtil.setStatus(false);
            resultUtil.setInfo("未登录，请先登录");
            resultUtil.setObj(null);
            return resultUtil;
        }
        UserBean user = JSONObject.parseObject(obj.toString(), UserBean.class);
        if(user == null){
            resultUtil.setStatus(false);
            resultUtil.setInfo("未登录，请先登录");
            resultUtil.setObj(null);
            return resultUtil;
        }

        List<Integer> idRealList = new ArrayList<>();
        for (String str: ids.split(",")) {
            idRealList.add(Integer.parseInt(str));
        }
        List<EnterpriseBean> beforeDelete = enterpriseService.findByIdIn(idRealList);
        List<String> uuidList = new ArrayList<>();
        // 日志的处理
        List<DataLogBean> logs = new ArrayList<>();
        for (EnterpriseBean beforeDeleteBean : beforeDelete) {
            uuidList.add(beforeDeleteBean.getUuid());
            DataLogBean log = new DataLogBean();
            log.setUserUuid(user.getUuid());
            log.setUserName(user.getUserRealName());
            log.setOperateTime(DateUtil.DateToStr(new Date(), "yyyy-MM-dd HH:mm:ss"));
            log.setDataTuid(beforeDeleteBean.getUuid());
            log.setDataTitle(beforeDeleteBean.getEntName());
            log.setOriginalContent(JSON.toJSONString(beforeDeleteBean));
            log.setOperateRemarks("该企业资源及其方案、进度等相关资料均以删除！");
            log.setLogType(0);
            log.setDetailedType(0);
            logs.add(log);
        }
        boolean success = this.enterpriseService.deleteByIdIn(idRealList, uuidList, user);
        logService.saveAllBoolean(logs);
        if(!success) {
            resultUtil.setInfo("操作失败!");
            resultUtil.setStatus(success);
            resultUtil.setObj(null);
            return resultUtil;
        }
        resultUtil.setInfo("操作成功");
        resultUtil.setStatus(success);
        resultUtil.setObj(null);
        return resultUtil;
    }
    
    /**
     * 批量单一授权
     * @author lxw
     * @date 2019年4月9日
     * @param request
     * @param session
     * @param uuids 资源UUIDS
	 * @param suuid 查看权限用户UUIDS
	 * @param sname查看权限用户名称集
	 * @param euuid编辑 权限用户UUIDS
	 * @param ename编辑权限用户名称集
	 * @param user 当前操作用户
     * @return
     */
    @RequestMapping(value="/empowerByIds", method = RequestMethod.POST)
    public ResultUtil empowerByIds(HttpServletRequest request, HttpSession session, String uuids,String suuid,String sname,String euuid,String ename){
        ResultUtil resultUtil = new ResultUtil();
        Object obj = session.getAttribute("user");
		UserBean user = JSONObject.parseObject(obj.toString(), UserBean.class);
		if(user==null){
			resultUtil.setStatus(false);
			resultUtil.setInfo("用户未登录，请先登录！");
			resultUtil.setObj(null);
			return resultUtil;
		}
        boolean success = this.enterpriseService.empowerByIds(uuids, suuid, sname, euuid, ename, user);
        resultUtil.setInfo(success?"操作成功":"操作失败");
        resultUtil.setStatus(success);
        resultUtil.setObj(null);
        return resultUtil;
    }
    
    /**
	 * 设置企业的启动或者终止
	 * @author lxw
	 * @date 2019年4月19日
	 * @param isEnd 0、正常，1、终止
	 * @param uuids
	 * @return
	 */
    @RequestMapping(value="/setEntStartOrEnd", method = RequestMethod.POST)
    @ResponseBody
	public ResultUtil setEntStartOrEnd(HttpServletRequest request,HttpSession session,Integer isEnd, String uuids){
    	Object obj = session.getAttribute("user");
		UserBean user = JSONObject.parseObject(obj.toString(), UserBean.class);
		return this.enterpriseService.setEntStartOrEnd(user,isEnd,uuids);
	}
    
    /**
     * 重置负责人
     * @author lxw
     * @date 2019年4月26日
     * @param request
     * @param session
     * @param userUuid
     * @param userName
     * @param uuids
     * @return
     */
    @RequestMapping(value="/resetLiableUserByUuids", method = RequestMethod.POST)
    @ResponseBody
	public ResultUtil resetLiableUserByUuids(HttpServletRequest request,HttpSession session, String userUuid, String userName, String uuids){
    	Object obj = session.getAttribute("user");
		UserBean user = JSONObject.parseObject(obj.toString(), UserBean.class);
		return this.enterpriseService.resetLiableUserByUuids(user, uuids, userUuid, userName);
	}
    
    /**
     * 导出表格
     * @param request
     * @param response
     * @param session
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value="/exportExcel", method = RequestMethod.POST)
	public void resetLiableUserByUuids(HttpServletRequest request,HttpServletResponse response,HttpSession session) throws Exception{
    	Object obj = session.getAttribute("user");
		UserBean user = JSONObject.parseObject(obj.toString(), UserBean.class);
		String datas=request.getParameter("datas");
		JSONObject dataObj=JSONObject.parseObject(datas);
		PageVo vo=new PageVo();
		vo.setPageSize(Integer.parseInt(dataObj.getString("pageSize")));
		vo.setPageIndex(Integer.parseInt(dataObj.getString("pageIndex")));
		vo.setOrderBy(dataObj.getString("orderBy"));
		vo.setOrderDesc(Integer.parseInt(dataObj.getString("orderDesc")));
		ResultPageUtil ru=retrievalService.comSearch(dataObj.getString("table"), dataObj.getString("text"), dataObj.getString("higthText"),vo, user);
		Map<String,Object> map=new HashMap<>();
		map.put("rows", JSON.toJSONString(ru.getRows()));
		map.put("column", dataObj.getString("column"));
		map.put("type","enter");
		try {
			MyFileUtil.exp(request, response, JSON.toJSONString(map));
		} catch (IOException e) {
			throw new Exception("导出文件错误",e);
		}
	}
}
